package com.yy.utils;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;

/**
 * @Description:
 * @ClassName: SecretUtil
 * @author: 姚欣宏
 * @date: 2023.07.10
 */
public class SecretUtil {
    private static String KEY = "87R6W73IO8C43P32";
    private static String IV = "T7K702065Y9BZSZU";
    public static final String ENCODING = "utf-8";

    public static String encrypt(String data) {
        return encrypt(data, KEY, IV);
    }

    public static String desEncrypt(String data) {
        return desEncrypt(data, KEY, IV);
    }

    private static String encrypt(String data, String key, String iv) {
        try {
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes("utf-8"), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes("utf-8"));
            cipher.init(1, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(data.getBytes("utf-8"));
            return (new Base64()).encodeToString(encrypted);
        } catch (Exception var7) {
            var7.printStackTrace();
            return null;
        }
    }

    private static String desEncrypt(String data, String key, String iv) {
        try {
            byte[] encrypted1 = (new Base64()).decode(data);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
            cipher.init(2, keySpec, ivSpec);
            byte[] original = cipher.doFinal(encrypted1);
            return (new String(original)).trim();
        } catch (Exception var8) {
            var8.printStackTrace();
            return null;
        }
    }

    public static String getImageId(String data) {
        String result = "";

        for(int i = 0; i < data.length(); ++i) {
            if (i % 2 == 0) {
                result = result + data.split("")[i];
            }
        }

        return result;
    }

    public static void main(String[] args) {
        System.out.println(encrypt(getImageId("r1ndxs9vrp7rgvaeo4fo307njew7d1ez")));
    }
}
